# 导入APIView
from rest_framework.views import APIView

# 导入数据模型
from users.models import User

# 导入drf返回 response模块
from rest_framework.response import Response

# 导入自定义密码加密模块
from libs.md5 import md5

class CustomAuthToken(APIView):

    def post(self, request, *args, **kwargs):
        # 接收前端提交的数据
        username = request.data.get('username')
        # 接收前端提交数据密码，进行hash加密与数据库进行对比，验证密码是否正确
        password = md5(request.data.get("password"))

        if not username:
            result = {'code': 500, 'msg': '用户名为空'}
            return Response(result)

        try:
            user_obj = User.objects.get(username=username)
            password_list = user_obj.password
            username_list = user_obj.username
            name_list = user_obj.name
            status_list = user_obj.status
            token = user_obj.token.token_key

            if status_list != '启用':
                result = {'code': 500, 'msg': '用户被禁止登陆，请联系管理员！'}
                return Response(result)

            if username_list == username and password_list == password:
                try:
                    roles = user_obj.role.role
                    res = {'code': 200, 'msg': '认证成功', 'token': token, 'username': username, 'name': name_list, 'roles': roles}
                    return Response(res)
                except Exception as e:
                    res = {'code': 500, 'msg': "角色不存在，请联系管理员绑定后登陆 %s" % e}
                    return Response(res)
            else:
                res = {'code': 500, 'msg': '用户密码错误，请核对后在输入'}
                return Response(res)
        except Exception as e:
            res = {'code': 500, 'msg': "用户名不存在 %s" % e }
            return Response(res)

class ChangePassword(APIView):
    def post(self, request, *args, **kwargs):
        print(request.data)
        # 获取用户名
        username = request.data.get("username")

        # 获取新密码
        new_password = md5(request.data.get("new_password"))


        if not username:
            result = {'code': 500, 'msg': '用户名为空'}
            return Response(result)

        try:
            user_obj = User.objects.get(username=username)
            user_password = user_obj.password
        except:
            res = {'code': 500, 'msg': '用户不存在！'}
            return Response(res)

        if user_password:
            user_obj.password = new_password
            user_obj.save()
            res = {'code': 200, 'msg': '修改密码成功'}
        else:
            res = {'code': 500, 'msg': '修改密码失败'}

        return Response(res)